/**
 * Fetch请求工具类
 * 基于原生Fetch API的请求封装
 */

/**
 * Fetch请求类
 */
class FetchRequest {
  constructor(config) {
    this.config = config;
  }

  /**
   * 发送请求
   */
  async send() {
    const { url, method = 'GET', headers = {}, data, timeout = 10000 } = this.config;

    // 构建请求配置
    const fetchConfig = {
      method,
      headers: new Headers(headers),
      credentials: this.config.withCredentials ? 'include' : 'same-origin'
    };

    // 添加请求体
    if (data) {
      if (data instanceof FormData) {
        fetchConfig.body = data;
      } else if (typeof data === 'object') {
        fetchConfig.headers.set('Content-Type', 'application/json');
        fetchConfig.body = JSON.stringify(data);
      } else {
        fetchConfig.body = data;
      }
    }

    // 创建超时控制器
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);
    fetchConfig.signal = controller.signal;

    try {
      const response = await fetch(url, fetchConfig);
      clearTimeout(timeoutId);

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const responseData = await this.parseResponse(response);
      const responseHeaders = {};
      response.headers.forEach((value, key) => {
        responseHeaders[key] = value;
      });

      return {
        data: responseData,
        status: response.status,
        statusText: response.statusText,
        headers: responseHeaders,
        config: this.config
      };
    } catch (error) {
      clearTimeout(timeoutId);
      throw error;
    }
  }

  /**
   * 解析响应数据
   */
  async parseResponse(response) {
    const responseType = this.config.responseType || 'json';

    switch (responseType) {
      case 'json':
        return await response.json();
      case 'text':
        return await response.text();
      case 'blob':
        return await response.blob();
      case 'arraybuffer':
        return await response.arrayBuffer();
      default:
        return await response.text();
    }
  }
}

/**
 * Fetch客户端类
 */
class FetchClient {
  constructor(config = {}) {
    this.baseURL = config.baseURL || '';
    this.timeout = config.timeout || 10000;
    this.headers = config.headers || {};
    this.withCredentials = config.withCredentials || false;
  }

  /**
   * 发送请求
   */
  async request(config) {
    // 处理URL
    const url = config.url.startsWith('http') ? config.url : this.baseURL + config.url;

    // 合并配置
    const finalConfig = {
      ...config,
      url,
      timeout: config.timeout || this.timeout,
      headers: { ...this.headers, ...config.headers },
      withCredentials: config.withCredentials ?? this.withCredentials
    };

    const request = new FetchRequest(finalConfig);
    return request.send();
  }

  /**
   * GET请求
   */
  async get(url, params, config) {
    const queryString = params ? '?' + new URLSearchParams(params).toString() : '';
    return this.request({
      ...config,
      url: url + queryString,
      method: 'GET'
    });
  }

  /**
   * POST请求
   */
  async post(url, data, config) {
    return this.request({
      ...config,
      url,
      method: 'POST',
      data
    });
  }

  /**
   * PUT请求
   */
  async put(url, data, config) {
    return this.request({
      ...config,
      url,
      method: 'PUT',
      data
    });
  }

  /**
   * DELETE请求
   */
  async delete(url, config) {
    return this.request({
      ...config,
      url,
      method: 'DELETE'
    });
  }

  /**
   * PATCH请求
   */
  async patch(url, data, config) {
    return this.request({
      ...config,
      url,
      method: 'PATCH',
      data
    });
  }
}

/**
 * 创建Fetch客户端
 */
function createFetchClient(config) {
  return new FetchClient(config);
}

/**
 * 快速Fetch请求方法
 */
const fetch = {
  /**
   * 创建Fetch客户端
   */
  createClient: createFetchClient,
  
  /**
   * 快速GET请求
   */
  get: async (url, params) => {
    const client = createFetchClient();
    return client.get(url, params);
  },
  
  /**
   * 快速POST请求
   */
  post: async (url, data) => {
    const client = createFetchClient();
    return client.post(url, data);
  },
  
  /**
   * 快速PUT请求
   */
  put: async (url, data) => {
    const client = createFetchClient();
    return client.put(url, data);
  },
  
  /**
   * 快速DELETE请求
   */
  delete: async (url) => {
    const client = createFetchClient();
    return client.delete(url);
  }
};

// 导出
if (typeof module !== 'undefined' && module.exports) {
  module.exports = { FetchClient, FetchRequest, createFetchClient, fetch };
} else if (typeof window !== 'undefined') {
  window.fetch = fetch;
  window.FetchClient = FetchClient;
  window.FetchRequest = FetchRequest;
  window.createFetchClient = createFetchClient;
}
